<?php
/**
*
*	基本函数库 @zairwolf
*	所有函数名格式统一为首字母不大写，第二单词大写的命名方式
*/

if(!defined('IN')) exit('Access Denied');

//--------------------------------标准函数----------------------------------

function csubstr($str,$start,$end){
	$start = floor($start/2);
	$end = floor($end/2);
	return mb_substr($str,$start,$end,'utf-8');
}

//分页函数 ok
function Page($total, $pagesize, $rewrite = true, $onlyoutput = true, $param = false, $styleMode = 0, $pvar = 'page', $current = false){
	include_once ROOT.'include/Page.cls.php' ;
	if(empty($pagesize) || $pagesize<1) $pagesize=20;
	$obj = new Page($total, $pagesize, $current,$pvar);
	$obj->rewrite = $rewrite ;
	$obj->styleMode = $styleMode ;
	if(is_array($param) && !empty($param)) $obj->setVar($param);

	if($onlyoutput) return $obj->output(1);
	$output = array();
	$output['output'] = $obj->output(1);
	$output['limit'] = $obj->limit();
	$output['between'] = $obj->between();
	return $output ;
}

//只要三位ip函数 ok
function ipShow($ip){
	$ip = explode('.', $ip);
	$ip[3] = '*';
	return implode('.', $ip);
}

//循环强制停止函数 ok
function stopmark(){
	$file=ROOT.'data/cache/stop.txt';
	if(file_exists($file)) {
		if(time()-filemtime($file)>60) unlink($file);
		else exit;
	}
}

//日志记录功能 ok
function addLog($logcon, $type = '', $logcon2 = ''){
	global $_G;

	$typeArr=array("password", "money", "group", "action", "access", "systemerror", "sql" );
	if(defined('IN_ACP') && !$type) $type="action";//后台默认为action
	if(!in_array($type,$typeArr)) $type="other";//其它默认


	switch($type) {
		case 'password':
		case 'action':
		case 'sql':
			$logcon .= "|\tR--".$logcon2;
		default :
			$logcon = $_G['user_name']."|\tR--".$logcon."|\tR--".TIMESTAMP."|\tR--".$_G['user_ip'];
			if(!is_file(ROOT."data/log/$type.log.php"))
				if(!rfow(ROOT."data/log/$type.log.php", "<?php exit('Access Denied'); ?>\n"))
					exit('Can\'t Create Log File, Check Write Permission (Floder)./data/log/');

			if(!write(ROOT."data/log/$type.log.php", $logcon."\n"))
				exit('Can\'t Write Log, Check Write Permission (File),.data/log/'.$type.'.log.php');
			break;
	}
}

//检查过滤 ok
function banList($str, $kind='word'){
	if(!$str || empty($GLOBALS['_CACHE']['banlist'][$kind]) || !is_array($GLOBALS['_CACHE']['banlist'][$kind])) Return false;
	foreach($GLOBALS['_CACHE']['banlist'][$kind] as $val){
		if($kind=='word' && strstr($str,$val)) Return true;
		if($kind!='word' && $str==$val) Return true;
	}
	Return false;
}


//--------------------------------登录相关函数----------------------------------

//检查是否登录 ok
function login($return = false){
	global $_G;
	if($return) return $_G['user_id'];
	if(!$_G['user_id']) b('本操作需要登录后操作。您的登录信息超时，请先登录:)');
}

//判断是否有后台的管理权限
function checkacp(){
	global $_G,$_SYSTEM;
	if(!login(true)) Return false;

	if(!$admin=db_r("select * from rd8_user_acp where user_id='$_G[user_id]'")) Return false;

	if($admin['isfounder']) return true;
	$args = func_get_args();//细分权限 2009-4-29 @zairwolf 23:29 ok
	$adminpriv = explode(',', $admin['privilege']);
	if(!empty($args) && in_array(implode('_', $args), $adminpriv)){
		Return true;
	}
	if(db_r("select * from rd8_session_acp where acp_id='$admin[id]' and lasttime>=".(TIMESTAMP-$_SYSTEM['SAFE']['acp_expire']*60))) return true;//细分后应该去掉该处

	Return false;
}

//-----------------------------权限检查/安全函数----------------------------

//是否允许访问的ip组 ok
function ipAccess($ial, $allow=true){//ial(ip access list) as array, allow in allow,deny / deny,allow
	global $_G;
	$uip = explode('.', $_G['user_ip']);
	if(empty($uip) || empty($uip[0]) || empty($uip[1]) || empty($uip[2]) || empty($uip[3])) return false;

	if(!is_array($ial)) $ial = explode("\n", $ial);
	foreach($ial as $key => $ip) $ial[$key] = explode('.', $ip);

	foreach($ial as $key => $ip) for($i = 0; $i <= 3; $i++) if(empty($ip[$i])) $ial[$key][$i] = $uip[$i];

	$result = $allow;
	foreach($ial as $ip) {
		if($allow) {
			$result = $result && ($ip == $uip ? !$allow : $allow);
		}else {
			$result = $result || ($ip == $uip ? !$allow : $allow);
		}
	}
	return $result;
}

function _htmlspecialchars($string){
	if(is_array($string)) foreach($string as $key => $val) $string[$key] = _htmlspecialchars($val);
	else $string = str_replace(array('&', '<', '>', '"', "'", ' ', "\r\n", "\n", "\t"), array('&amp;', '&lt;', '&gt;', '&quot;', '\\\'', '&nbsp;', '<br />', '<br />', '&nbsp;&nbsp;&nbsp;&nbsp;'), $string);
	return $string;
}

//------------------------提示页面函数-----------------------------

//错误提示函数 ok
function b($msg, $external = 3){//1 - header 2 - back 4 - login
	global $Global, $_SYSTEM;

	$external = sprintf("%03b",$external);
	$header = $external[2] ? (defined('IN_ACP') ? 0 : 1) : 0;
	if($header) _header('错误提示');
	if(defined('IN_ACP')) acpheader();//后台header输出 
	if(!empty($Global['oldstyle'])) $Global['style'] = $Global['oldstyle'];

	$forward = explode('/', substr($_SYSTEM['SYSTEM']['SITE_ADDR'], 7));
	$forward = 'http://'.$forward[0].$_SERVER['REQUEST_URI'];
	//显示
	$tpl = new Tpl('error');
	$tpl->assign(array(
		'forward' => $external[1] ? urlencode($forward) : '',
		'login' => $external[0] ? 'login' : '',
		'C_loghashenable' => _secode(1),
		'msg' => $msg,
	));
	$tpl->output();
	if($header) _footer();
	exit;
}

//跳转页面函数 ok
function j($URL,$title=''){
	global $Global;
	//if(!empty($Global['oldstyle'])) $Global['style'] = $Global['oldstyle'];
	$header = defined('IN_ACP') ? 0 : 1;
	if($header) _header('页面跳转');
	if(defined('IN_ACP')) acpheader();//后台header输出

	$tpl = new Tpl('jumpage');
	$tpl->assign(array(
		'URL' => $URL,
		'title' => $title,
	));
	$tpl->output();
	if($header) _footer();
	exit;
}

//警告框函数 ok
function alert($con, $refresh=0) {
	$output = 'alert("'.str_replace('"','&quot;',$con).'");';
	if($refresh == 1) $output = 'parent.window.refresh();';
	elseif($refresh == -1) $output = 'window.close();';
	elseif($refresh) $output = "parent.window.location='$refresh';";

	exit('<script type="text/javascript">'.$output.'</script>');
}

function _addslashes($string){
	if(is_array($string)) {
		foreach($string as $k => $v) {
			$string[$k] = _addslashes($v);
		}
	}else {
		$string = addslashes($string);
	}

	return $string;
}

//--------------------------------COOKIE函数----------------------------------
//存储cookie(可存储数组)
function cookie($name, $value = '', $expire = 0, $path = '/', $domain = '', $secure = false, $httponly = false){
	global $_G,$_SYSTEM;

	if(!$domain) {//让作用域为.xx.com
		$domain=parse_url($_SYSTEM['SYSTEM']['SITE_ADDR']);
		$domain=explode('.',$domain['host']);
		$domain=$domain[count($domain)-2].".".$domain[count($domain)-1];
	}

	if(!empty($value)){
		if(!is_array($value)) $value=array('!@#$zairwolf',$value);//若非数组则构建数组以便序列化
		$hash = md5($name.base64_encode(serialize($value)).'zairwolf'.ipShow($_G['user_ip']));
		$value = base64_encode(serialize(array($value,$hash)));
	}
	
	if($expire > 0) $expire = TIMESTAMP + $expire;
	setcookie($name, $value, $expire, $path, $domain);
}

//读取cookie
function _cookie($name){
	global $_G;
	if(!isset($_COOKIE[$name])) Return null;
	else $cookie = $_COOKIE[$name];
	$cookie = @unserialize(@base64_decode(stripslashes($cookie)));
	$hash=md5($name.base64_encode(serialize($cookie[0])).'zairwolf'.ipShow($_G['user_ip']));
	if($cookie[1] != $hash) Return null;
	//检测通过,输出值
	if($cookie[0][0]=='!@#$zairwolf') Return $cookie[0][1];
	Return $cookie[0];

}

//email函数
function sendmail($target, $title, $content){
	$headers = 
		"From: luciferclub@126.com\r\n" .
		"Reply-To: luciferclub@126.com\r\n" .
		"Content-type: text/html; charset=gbk";
	$title=mb_convert_encoding($title, 'gbk', 'utf-8');
	$content=mb_convert_encoding($content, 'gbk', 'utf-8');
	mail($target, $title, $content, $headers);	
}

//用戶積分函數
function vmoney($num,$uid=0){
	global $_G;
	if((!$_G['user_id'] && !$uid)){
		Return false;
	}
	$num = number_format($num, 2, '.', '');
	db_q("update rd8_user set vmoney=vmoney+$num where id=".($uid?$uid:$_G['user_id']));
	Return true;
}

//得到_GET变量
function _get($var){
	return isset($_GET[$var]) ? (MAGIC_QUOTES ? $_GET[$var] : _addslashes($_GET[$var])) : null;
}

//得到_POST变量
function _post($var){
	return isset($_POST[$var]) ? (MAGIC_QUOTES ? $_POST[$var] : _addslashes($_POST[$var])) : null;
}

//得到_GET或_POST变量
function _get_post($var){
	if($var2=_get($var)){
		Return $var2;
	}
	if($var2=_post($var)){
		Return $var2;
	}
	Return null;
}

function json($con){
	exit(json_encode($con));
}

function rdate($timestamp = false, $format = 'Y-m-d H:i:s'){
	global $_SYSTEM;

	if(false === $timestamp) $timestamp = TIMESTAMP;
	return gmdate($format, $timestamp + $_SYSTEM['SYSTEM']['TIME_ZONE'] * 3600 + $_SYSTEM['SYSTEM']['TIME_DELAY']);
}
function rtodaytime($timestamp = false){
	global $_SYSTEM;

	$times = explode('-', rdate($timestamp, 'Y-m-d'));
	return gmmktime(0, 0, 0, $times[1], $times[2], $times[0]) - $_SYSTEM['SYSTEM']['TIME_ZONE'] * 3600 - $_SYSTEM['SYSTEM']['TIME_DELAY'];
}

function sizecount($filesize, $short = false) {
	if($filesize >= 1073741824) {
		$filesize = round($filesize / 1073741824 * 100) / 100 . ' G';
	}elseif($filesize >= 1048576) {
		$filesize = round($filesize / 1048576 * 100) / 100 . ' M';
	}elseif($filesize >= 1024) {
		$filesize = round($filesize / 1024 * 100) / 100 . ' K';
	}else {
		$filesize = $filesize . ' B'.($short ? '' : 'ytes');
	}
	return $filesize;
}

function rrand($len, $type = 7, $limit = false) {//1 - Number //2 - Lower Char //4 - Upper Char //8 - Chinese
	mt_srand((double)microtime() * 1000000);
	switch($type) {
		case 1:
			$charlist = '0123456789';
			break;
		case 2:
			$charlist = 'abcdefghijklmnopqrstuvwxyz';
			break;
		case 3:
			$charlist = '0123456789abcdefghijklmnopqrstuvwxyz';
			break;
		case 4:
			$charlist = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
			break;
		case 5:
			$charlist = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
			break;
		case 6:
			$charlist = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
			break;
		case 7:
			$charlist = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
			break;
		case 8://使用中文
			global $Ccharlist;
			if(!$Ccharlist) $Ccharlist = file_get_contents(ROOT."include/disturbTxt.lib");
			break;
	}
	$str = '';
	if($type == 8) {
		$max = strlen($Ccharlist) / 3-1;
		for($i = 0; $i < $len; $i++) $str .= substr($Ccharlist,mt_rand(0, $max)*3,3);
		//$str = mb_convert_encoding($str,'utf-8','gbk');
	}else {
		$max = strlen($charlist) - 1;
		for($i = 0; $i < $len; $i++) $str .= $charlist[mt_rand(0, $max)];
		if($type == 1 && $limit !== false) while($str > $limit) $str = rrand($len, $type, $limit);
	}
	return $str;
}

function ris_int($var){
	return is_numeric($var) && floor($var) == $var;
}

//---------验证码---------//

function _secode($bit){// 2 - register  1 - login  0 - comment
	global $_SYSTEM;

	$b = sprintf('%03b', $_SYSTEM['SAFE']['secode']);

	return $_SYSTEM['SAFE']['secode_length'] && $b[$bit];
}
function _secode_check($bit, $secode){
	global $sid;

	if(!_secode($bit)) return true;

	if(!$secode) return false;

	if($row = db_r("select secode from rd8_session where sid='".md5($sid)."'")) {
		db_q("update rd8_session set secode='' where sid='".md5($sid)."'");
	}
	if(!$row || !$row['secode']) return false;

	return strtolower($row['secode']) == strtolower($secode);
}

function _secode_generate(){
	global $_SYSTEM, $sid;

	$secode = rrand($_SYSTEM['SAFE']['secode_length'], 1);
	db_q("update rd8_session set secode='$secode' where sid='".md5($sid)."'");

	$im = ImageCreate($_SYSTEM['SAFE']['secode_length'] * 9 + 3, 16);

	$bg = ImageColorAllocate($im, 236, 233, 216);
	$font_color=ImageColorAllocate($im, 0, 0, 0);
	$gray = ImageColorAllocate($im, 200, 200, 200);
	ImageFill($im, 0, 0, $gray);
	for($i = 0; $i < 300; $i++) {
		$randcolor = ImageColorallocate($im, rrand(3, 1, 255), rrand(3, 1, 255), rrand(3, 1, 255));
		ImageSetPixel($im, rrand(2, 1), rrand(2, 1, 29), $randcolor);
	}
	ImageString($im, 5, 2, 0, $secode, $font_color);
	header('Content-type: image/png');
	ImagePNG($im);
	ImageDestroy($im);
	exit;
}

//合并sql语句
function sqlcol($cols){
	$colarr=array();
	foreach($cols as $key=>$val){
		$colarr[]="$key='$val'";
	}
	return implode(',', $colarr);
}

//字符串截取函数
function rsubstr($string, $after = false, $before = ''){
	if(false === $after) {
		$sp = 0;
	}elseif(!$after) {
		return false;
	}else {
		$sp = strpos($string, $after);
	}
	if(false === $sp)
		return false;

	$sp += strlen($after);

	if($before) {
		$ep = strpos($string, $before, $sp);
	}else {
		$ep = 0;
	}
	if(false === $ep)
		return false;

	if($ep) {
		return substr($string, $sp, $ep - $sp);
	}else {
		return substr($string, $sp);
	}
}

